package com.eascs.web.o2o.report.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.notify.constant.ModelResult;
import com.eascs.notify.mail.MailNotifyRequest;
import com.eascs.notify.mail.MailNotifyResponse;

@Component
public class MailUtil {

	private final Logger logger = LoggerFactory.getLogger(MailUtil.class);

	@Value("${email.host}")
	private String host;
	@Value("${email.fromemail}") 
	private String userName;
	@Value("${email.fromemailpd}")
	private String passWord;
	@Value("${email.fromemail}")
	private String from;
	
	
	public ModelResult<MailNotifyResponse> sendMail(MailNotifyRequest mailNotifyRequest) {
		Transport transport = null;
		ModelResult<MailNotifyResponse> model = new ModelResult<MailNotifyResponse>();
		MailNotifyResponse mailNotifyResponse = null;
		try {
			logger.info("start send mail...");
			//设置属性
			Properties props=new Properties();
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.auth", "true");
			//建立会话
			Session session = Session.getDefaultInstance(props, new Authenticator() {
				public PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(userName,passWord);
				}
			});
			//建立信息(构造MimeMessage 并设定基本的值)
			MimeMessage msg = new MimeMessage(session);
			if(StringUtil.isBlank(mailNotifyRequest.getFrom())){
				msg.setFrom(new InternetAddress(from));//发件人
			}else{
				msg.setFrom(new InternetAddress(mailNotifyRequest.getFrom()));//发件人
			}
			msg.setSubject(transferChinese(mailNotifyRequest.getTitle()));//主题
			
			if(StringUtil.isNotBlank(mailNotifyRequest.getRecipientTo())){
				msg.setRecipients(Message.RecipientType.TO, new InternetAddress().parse(mailNotifyRequest.getRecipientTo())); // 收件人 
			}
			if(StringUtil.isNotBlank(mailNotifyRequest.getRecipientCc())){
				msg.setRecipients(Message.RecipientType.CC, new InternetAddress().parse(mailNotifyRequest.getRecipientCc())); // 抄送人  
			}
			if(StringUtil.isNotBlank(mailNotifyRequest.getRecipientBcc())){
				msg.setRecipients(Message.RecipientType.BCC,new InternetAddress().parse(mailNotifyRequest.getRecipientBcc())); // 密送人 
			}
			
			// 构造Multipart
			Multipart mp = new MimeMultipart();
			// 向Multipart添加正文
			MimeBodyPart mbpContent = new MimeBodyPart();
			mbpContent.setContent(mailNotifyRequest.getContent(), "text/html;charset=UTF-8");
			// 向MimeMessage添加（Multipart代表正文）
			mp.addBodyPart(mbpContent);//正文
			
			//附件
			if (null != mailNotifyRequest.getAttachmentPath()) {
				String[] attach =mailNotifyRequest.getAttachmentPath().split(",");
				if(attach!=null&&attach.length>0){
					for (String directory : attach) {
						logger.info("send mail with dir {}", directory);
						File[] files = new File(directory).listFiles();
						List<String> fileNames = new ArrayList<>();
						for (int i = 0; null != files && i < files.length; i++) {
							File file = files[i];
							if (file.isFile())
								fileNames.add(file.getAbsolutePath());
						}
						attachmentFiles(mp, fileNames);
					}
				}
			}
			// 向Multipart添加MimeMessage
			msg.setContent(mp);
			msg.setSentDate(new Date());
			msg.saveChanges();
			

			// 发送邮件
			transport = session.getTransport("smtp");
			transport.connect(host,userName,passWord);
			transport.sendMessage(msg, msg.getAllRecipients());
			mailNotifyResponse = new MailNotifyResponse();
			mailNotifyResponse.setResponseId(mailNotifyRequest.getRequestId());
			mailNotifyResponse.setResponseDateTime(mailNotifyRequest.getRequestDateTime());
			model.setModel(mailNotifyResponse);
			logger.info("send mail success...");
			
		} catch (Exception e) {
			mailNotifyResponse=null;
			logger.error("邮件发送异常,异常信息为:[{}]", e);
			return model.withError("发送异常","邮件发送异常...");
		}finally {
			closeTransport(transport);
		}
		return model;
	}

	private void closeTransport(Transport transport) {
		if (transport != null) {
			try {
				transport.close();
			} catch (MessagingException e) {
				logger.error("send mail error...", e);
			}
		}
	}

	private void attachmentFiles(Multipart mp, List<String> attches) throws MessagingException, UnsupportedEncodingException {
		if (attches != null && !attches.isEmpty()) {
			for (String attach : attches) {
				logger.info("set email attche: {}", attach);
				MimeBodyPart mbpFile = new MimeBodyPart();
				FileDataSource fds = new FileDataSource(attach);
				DataHandler dh2 = new DataHandler(fds);
				mbpFile.setDataHandler(dh2);
				mbpFile.setFileName(transferChinese(fds.getName()));
				mp.addBodyPart(mbpFile);
			}
		}
	}
	
	private String transferChinese(String str) throws UnsupportedEncodingException {
		return MimeUtility.encodeWord(str);
	}
	
	
}
